package cn.hncu.booksManagementSystem.utils;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * Description:
 *	进行文件IO的工具类
 */
public class FileIoUtil {
	//私有化构造函数
	private FileIoUtil() {
	}
	/**
	 * 从文件中读取一个对象类型为Collection<E>的数据
	 * @param fileName 数据源的文件名称
	 * @return 一个对象类型为Collection<E>的数据
	 */
	public static<E> Collection<E> readFromDataBase(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			write2DataBase(new ArrayList<E>(), fileName);
		}
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			@SuppressWarnings("unchecked")
			Collection<E> col = (Collection<E>) ois.readObject();
			if (col==null) {
				col = new ArrayList<E>();
			}
			return col;
		}catch (EOFException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			if (ois!=null) {
				try {
					ois.close();
				} catch (IOException e) {
					throw new RuntimeException("数据库发生严重错误！", e);
				}
			}
		}
		return null;
	}
	/**
	 * 把集合中的数据写入到目标文件中
	 * @param col 被写入的对象(集合)
	 * @param fileName 目标文件名
	 * @return true-写入成功,false-写入失败
	 */
	public static<E> boolean write2DataBase(Collection<E> col , String fileName) {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(fileName));
			oos.writeObject(col);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					throw new RuntimeException("数据库发生严重错误！", e);
				}
			}
		}
		
		return false;
	}
}
